package com.edu.hbwe.book.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import com.edu.hbwe.book.dao.OrderItemDao;
import com.edu.hbwe.book.entity.Order;
import com.edu.hbwe.book.entity.OrderItem;
import com.edu.hbwe.book.entity.Product;
import com.edu.hbwe.book.util.DbUtil;



public class OrderltemDaolmpl implements OrderItemDao {

	@Override
	public void addOrderItem(Order order) throws SQLException {
		// 1.生成sql语句
		String sql = "insert into orderItem values(?,?,?)";

		QueryRunner runner = new QueryRunner();

		List<OrderItem> items = order.getOrderItems();

		Object[][] params = new Object[items.size()][3];

		for (int i = 0; i < params.length; i++) {
			params[i][0] = items.get(i).getOrder().getId();
			params[i][1] = items.get(i).getP().getId();
			params[i][2] = items.get(i).getBuynum();
		}

		runner.batch(DbUtil.getConnection(), sql, params);
	}

	@Override
	public List<OrderItem> findOrderItemByOrder(Order order) {
		String sql = "select * from orderItem,Products where products.id=orderItem.product_id and order_id=?";

		QueryRunner runner = new QueryRunner(DbUtil.getDataSource());

		try {
			return runner.query(sql, new ResultSetHandler<List<OrderItem>>() {
				public List<OrderItem> handle(ResultSet rs) throws SQLException {

					List<OrderItem> items = new ArrayList<OrderItem>();
					while (rs.next()) {
						OrderItem item = new OrderItem();

						item.setOrder(order);
						item.setBuynum(rs.getInt("buynum"));

						Product p = new Product();
						p.setCategory(rs.getString("category"));
						p.setId(rs.getString("id"));
						p.setDescription(rs.getString("description"));
						p.setImgurl(rs.getString("imgurl"));
						p.setName(rs.getString("name"));
						p.setPnum(rs.getInt("pnum"));
						p.setPrice(rs.getDouble("price"));
						item.setP(p);

						items.add(item);
					}

					return items;
				}
			}, order.getId());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void delOrderItems(String id) throws SQLException {
		String sql="delete from orderItem where order_id=?";
		
		QueryRunner runner=new QueryRunner();
		
		runner.update(DbUtil.getConnection(),sql,id);
	}

}
